package com.globagames.strategicgames.view.battles.actions
{
	import com.globagames.isometric.core.event.IsoMapMouseEvent;
	import com.globagames.isometric.core.model.IsoTile;
	import com.globagames.isometric.core.util.CollisionManager;
	import com.globagames.isometric.core.view.actions.IAction;
	import com.globagames.strategicgames.model.Soldier;
	import com.globagames.strategicgames.model.StrategicGameModelLocator;
	import com.globagames.strategicgames.util.SoldierDesigner;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.controls.Image;
	import mx.core.UIComponent;
	
	import org.cove.ape.APEngine;
	import org.cove.ape.CircleParticle;
	

	[Event(name="dropSucceed")]
	[Event(name="dropFailed")]
			
	public class DragAndDropAction extends UIComponent implements IAction {
		private var model:StrategicGameModelLocator = StrategicGameModelLocator.getInstance();
		public var _soldier:Soldier;
		public var proxyImage:Image;
		
		public var isoTileCharacterCenter:IsoTile;
		public var ar:Array;
		
		
		var lastMouseX:int = -1;
		var lastMouseY:int = -1;
		public function DragAndDropAction() {	
			proxyImage = new Image();	
			proxyImage.visible = false;
			addChild(proxyImage);
		}
		override protected function createChildren():void{
			x = 0;
			y = 0;
			super.createChildren();			
		}
		
		public function mouseMoveHandler(event:MouseEvent):void {
			
			var mX:int = model.coreModel.isoMap.mouseX;
			var mY:int = model.coreModel.isoMap.mouseY;
			if( lastMouseX != -1 ) {
				var d:Number = CollisionManager.distance(mX,mY,lastMouseX,lastMouseY);
				if( d > 16 ) {
					var dd:Number = d/16;
					mX = lastMouseX + (mX - lastMouseX)/dd;
					mY = lastMouseY + (mY - lastMouseY)/dd;
				}
			} 
			lastMouseX = mX;
			lastMouseY = mY;
			var position:IsoMapMouseEvent = model.coreModel.isoMap.getCurrentMousePosition(mX,mY);
			if( position.isoTile ) {				
				trace("x,y="+position.point2d.x+","+position.point2d.y);	
				
				
				if(proxyImage.visible) {
					
					soldier.soldierId ="proxyImage";
					model.coreModel.isoMap.addIsoObject(soldier.soldierIso, soldier.soldierId );
					soldier.soldierIso.ox = position.point2d.x;
					soldier.soldierIso.oy = position.point2d.y;
					proxyImage.visible = false;
					isoTileCharacterCenter = position.isoTile;
					//model.coreModel.isoMap.removeAllAPE(ar);
					ar = model.coreModel.isoMap.populateAroundAPE(isoTileCharacterCenter);
				} else {
					if( Math.abs(position.isoTile.x2d - isoTileCharacterCenter.x2d)>=2 
					||  Math.abs(position.isoTile.y2d - isoTileCharacterCenter.y2d)>=2 ) {
						isoTileCharacterCenter = position.isoTile;
						model.coreModel.isoMap.removeAllAPE(ar);
						ar = model.coreModel.isoMap.populateAroundAPE(isoTileCharacterCenter);
					}
				}				
				
				soldier.soldierIso.particle.px = position.point2d.x;
	            soldier.soldierIso.particle.py = position.point2d.y;
	            
	            APEngine.step();
		        //APEngine.paint();	      
		        
		        if( ! soldier.soldierIso.particle.hasCollided ) {
		        	var lastX2d:int = soldier.soldierIso.particle.px;
	            	var lastY2d:int = soldier.soldierIso.particle.py;
	            	
	            	if( Math.abs(lastX2d - soldier.soldierIso.ox) < 47 &&  Math.abs(lastY2d - soldier.soldierIso.oy) < 47) {
	            		if( proxyImage.visible == true ) proxyImage.visible = false;	
	            			        	
            			model.coreModel.isoMap.place(soldier.soldierIso, lastX2d,lastY2d);
            			model.coreModel.isoMap.isotile = model.coreModel.isoMap.testIsoTile(lastX2d,lastY2d);
	            		model.coreModel.isoMap.doRetraceIsotile = true;
			    		model.coreModel.isoMap.invalidateProperties();
			    		event.updateAfterEvent();
			    		
	            	}
		        				    	
		        } 
		      
		        
			}  
				
		}
		public function mouseUpHandler(event:MouseEvent):void {
			//trace("DragAndDropAction::mouseUpHandler");
			this.systemManager.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			this.systemManager.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
			
			model.coreModel.isoMap.removeAllAPE(ar);
			lastMouseX = -1;
			if( !proxyImage.visible ) {
				model.coreModel.isoMap.apeDefaultGroup.removeParticle(soldier.soldierIso.particle);
				soldier.soldierIso.particle.px = soldier.soldierIso.ox;
	            soldier.soldierIso.particle.py = soldier.soldierIso.oy;
	            soldier.soldierIso.particle.fixed = true;
	            model.coreModel.isoMap.apeDefaultGroup.addParticle(soldier.soldierIso.particle);
				dispatchEvent(new Event("dropSucceed"));
			}
			else {				
				model.coreModel.isoMap.apeDefaultGroup.removeParticle(soldier.soldierIso.particle);
				dispatchEvent(new Event("dropFailed"))	
			}
			
		}
		public function attach():void {
			proxyImage.alpha = 0.5;
			proxyImage.visible = true;	
			invalidateProperties();				
			this.systemManager.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			this.systemManager.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);	
			
			//model.coreModel.isoMap.populateAPE()
			/**var isoTile:IsoTile;	
			var i:int = 0;	
			for ( var y:int = 0 ; y < model.coreModel.isoMap.mapModule.sizeY ; y++ ) {
				for ( var x:int = 0 ; x < model.coreModel.isoMap.mapModule.sizeX ; x++ ) {
					isoTile = model.coreModel.isoMap.mapModule.tilesTable[y][x] as IsoTile;
					
					if( isoTile.design.length>1) {					
						trace("x,y="+x+","+y+" ");
						if( x > 38 && y > 70 ) {
							var r:RectangleParticle = new RectangleParticle(isoTile.x2d*32,isoTile.y2d*32,32,32,0,true);							
							model.coreModel.isoMap.apeDefaultGroup.addParticle(r);
							i++;
						}
					}
				}	
			}
			trace("attach ***  i="+i);	
			 * */
			soldier.soldierIso.particle = new CircleParticle(0, 0, 30);
        	soldier.soldierIso.particle.friction = 1;
			soldier.soldierIso.particle.elasticity = 1;
			soldier.soldierIso.particle.mass = 10;
			
			model.coreModel.isoMap.apeDefaultGroup.addParticle(soldier.soldierIso.particle);
				
			
			
					
		}
		public function detach():void {
			proxyImage.visible = false;					
		}
		
		public function get soldier ():Soldier {
			return _soldier;
		}
		
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {			
			super.updateDisplayList(unscaledWidth, unscaledHeight);				
		}
		override protected function commitProperties():void {
			super.commitProperties();
			if( model.coreModel.isoMap ) {
				proxyImage.move((model.coreModel.isoMap.mouseX -64 - 16),(model.coreModel.isoMap.mouseY - proxyImage.height +32));
				invalidateDisplayList();
			}			
		}
		

	}
}